package com.example.xinhuazidian.utils

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build

/**
 * 获取应用版本名称和版本号
 */
object AppVersionNameAndCode {
    /**
     * 获取当前App版本号
     */
    fun getVersionName(context: Context): String? {
        var versionName: String? = null
        val pm = context.packageManager
        val info: PackageInfo?
        try {
            info = pm.getPackageInfo(context.applicationContext.packageName, 0)
            if (info != null) {
                versionName = info.versionName
            }
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return versionName
    }

    /**
     * 获取当前App版本Code
     */
    fun getVersionCode(context: Context): Long {
        var versionCode: Long = 0
        val pm = context.packageManager
        val info: PackageInfo?
        try {
            info = pm.getPackageInfo(context.applicationContext.packageName, 0)
            if (info != null) {
                versionCode = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    //大于等于9.0系统获取版本号
                    info.longVersionCode
                } else {
                    //小于9.0系统获取版本号
                    info.versionCode.toLong()
                }
            }
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return versionCode
    }
}